package cn.xwb.yygh.service.hosp.controller;

import cn.xwb.yygh.common.util.exception.YyghException;
import cn.xwb.yygh.common.util.help.MD5;
import cn.xwb.yygh.common.util.result.Result;
import cn.xwb.yygh.common.util.result.ResultCodeEnum;
import cn.xwb.yygh.model.model.hosp.HospitalSet;
import cn.xwb.yygh.model.vo.hosp.HospitalSetQueryVo;
import cn.xwb.yygh.service.hosp.service.HospitalSetService;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.sun.org.apache.bcel.internal.generic.ARETURN;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.ReturnNode;
import org.apache.poi.util.StringUtil;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/*
医院设置接口
 */
@Api(tags = "医院设置管理")
//返回的json格式
@RestController
//请求路径
@RequestMapping("/admin/hosp/hospitalSet")
public class HospitalSetController {

//    自动装配service
    @Resource
    private HospitalSetService hospitalSetService;

    //接口1，查询医院设置表所有信息
    @GetMapping("findAll")
    @ApiOperation(value = "获取所有医院设置")
    public Result findAllHospitalSet(){
        //调用mybatis-plus自带的查询借口
        List<HospitalSet> list = hospitalSetService.list();
        return Result.ok(list);
    }

    //接口2，逻辑删除医院设置
    @ApiOperation(value="逻辑删除医院设置")
    @DeleteMapping("{id}")
    public  Result removeHospSet(@PathVariable Long id){    //PathVariable从动态地址栏获取id
        boolean flag = hospitalSetService.removeById(id);
        if(flag){
            return  Result.ok();
        }else{
            return  Result.fail();
        }
    }

    //接口3.条件查询分页
    @ApiOperation(value="条件的查询分页")
    @PostMapping("findPagHospSet/{current}/{limit}")
    public Result  findPagHospSet(@PathVariable long current, @PathVariable long limit,
                                  @RequestBody(required = false) HospitalSetQueryVo hospitalSetQueryVo){
       //创建page对象，传递当前页，每页记录页
        Page<HospitalSet> page = new Page<>(current,limit);
        //构建条件
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        String hosname = hospitalSetQueryVo.getHosname();//医院名称
        String hoscode = hospitalSetQueryVo.getHoscode();//医院编号

        if(!StringUtils.isEmpty(hosname)){  //当前传入的hosname不为空
            wrapper.like("hosname",hospitalSetQueryVo.getHosname());
        }
        if(!StringUtils.isEmpty(hoscode)){
            wrapper.eq("hoscode",hospitalSetQueryVo.getHoscode());
        }
        wrapper.orderByDesc("create_time"); //按照创建时间排序
        //调用方法实现分页查询
        Page<HospitalSet> pageHospitalSet = hospitalSetService.page(page,wrapper);
        //返回结果
        return Result.ok(pageHospitalSet);
    }

    //接口4.添加医院设置
    @ApiOperation(value="添加医院设置")
    @PostMapping("savaHospitalSet")
    public  Result saveHospitalSet(@RequestBody HospitalSet hospitalSet) throws Exception {
        //设置状态  0使用 1不能使用(数据库中设置的默认值为0，在这里可以不设置)
        hospitalSet.setStatus(0);
        //签名密钥
        Random random = new Random();
        //生成密钥规则：当前时间毫秒数 + 1000以内随机数
        String signKey = MD5.encrypt(System.currentTimeMillis()+ " " + random.nextInt(1000));
        //将密钥赋值给hospitalSet对象
        hospitalSet.setSignKey(signKey);
        //  调用service
        boolean save = hospitalSetService.save(hospitalSet);
        if(save){
            //TODD：调用短信发送业务方法

                send(hospitalSet.getContactsPhone(),"123456");

            return  Result.ok();

        }else {
            return Result.fail();
        }
    }

    //接口5.根据id获取医院设置
    @ApiOperation(value = "根据id获取医院设置")
    @GetMapping("getHospSet/{id}")
    public Result getHospSet(@PathVariable Long id){
            HospitalSet hospitalSet = hospitalSetService.getById(id);
            return  Result.ok(hospitalSet);
    }

    //接口6.修改医院设置
    @ApiOperation(value = "修改医院设置")
    @PostMapping("updateHospitalSet")
    public Result updateHospitalSet(@RequestBody HospitalSet hospitalSet){
        boolean flag = hospitalSetService.updateById(hospitalSet);
        if(flag){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //接口7.批量删除医院设置
    @ApiOperation(value = "批量删除医院设置")
    @DeleteMapping("batchRemove")
    public Result batchRemoveHospitalSet(@RequestBody List<Long> idList){

        hospitalSetService.removeByIds(idList);
        return Result.ok();
    }

    //8 医院设置锁定和解锁
    @ApiOperation(value = "医院设置锁定和解锁")
    @PutMapping("lockHospitalSet/{id}/{status}")
    public Result lockHospitalSet(@PathVariable Long id, @PathVariable Integer status) {
        //根据id查询医院设置信息
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        //设置状态
        hospitalSet.setStatus(status);
        //调用方法
        hospitalSetService.updateById(hospitalSet);
        return Result.ok();
    }

    //9 发送签名密钥
    @ApiOperation(value = "发送签名密钥")
    @PutMapping("sendKey/{id}")
    public Result sendHospitalSet(@PathVariable Long id) {
        //根据id获取医院设置对象
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        String signKey = hospitalSet.getSignKey(); //得到签名密钥
        String hoscode = hospitalSet.getHoscode(); //得到医院编号
        //TODO 发送短信
        try {
            send(signKey,hoscode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.ok();
    }

    /**
     * 发送短信
     * @param phoneNumbers
     * @param code
     * @throws Exception
     */
    private void send(String phoneNumbers,String code) throws  Exception{

        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tFfq8Lu16aVAJtvRDDM")
                .accessKeySecret("DNroPYDeCIF14sLXhddpaD72fSz0jF")
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shanghai") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("徐文波的个人博客")
                .phoneNumbers(phoneNumbers)
                .templateCode("SMS_268670985")
                .templateParam("{\"code\":\""+code+"\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }



    @ApiOperation(value = "全局异常处理测试")
    @GetMapping("test")
    public Result testGlobalException(){
        try {
            int i = 100/0;
        }catch (Exception e){
//            throw new YyghException(ResultCodeEnum.FAIL);
            throw new YyghException("零不能做除数", 333);
        }
        return Result.ok();
    }

}
